package com.wtgroup.demo.面试题;

import com.wtgroup.demo.common.util.SleepUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

/**
 * @author dafei
 * @version 0.1
 * @date 2021/3/7 17:50
 */
public class Q001 {
    /**实现容器, 提供两个方法 add, size
     * 线程1添加10个元素, 线程2监控个数, 达到5个时, 线程2给出提示并结束.
     *
     * Note: 能做到及时的提示结束吗?
     * t1 -- add -- size=5, unpark(t2), park 自己                  -- 继续... -- end
     * t2 -- park --                              通知, unpark(t1) -- end
     */

    static Thread t1 = null;
    static Thread t2 = null;
    public static void main(String[] args) throws InterruptedException {
        Container container = new Container();
        t2 = new Thread(() -> {
            while (container.size() != 5) {
                LockSupport.park();
                // 可能不能及时拿到最新的size
                SleepUtil.sleep(1);
            }
            System.out.println("[t2] 容器 size 达到 5"); // 给出提示时, size 已经改变了很多了
            LockSupport.unpark(t1);
        });
        t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                container.add(i);
                System.out.println("[t1] add " + i);
                if (container.size()==5) {
                    LockSupport.unpark(t2);
                    LockSupport.park(); // park 自己
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("!!!!!!!!!!!!!!!");
    }

    public static class Container {
        private List<Object> list = new ArrayList<>();

        public void add(Object item) {
            list.add(item);
        }

        public int size() {
            return list.size();
        }
    }
}
